#ifndef __UP_SEVER_HPP__
#define __UP_SEVER_HPP__
#include <iostream>
#include <string>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Logger.hpp"
#include "Common.hpp"
#include "Inet_host.hpp"

using namespace LogMudule;

const static int defsockfd = -1;
const static u_int16_t defport = 8888;
//const static std::string defip = "";
const static int defsize = 1024;

class UpSever
{
public:
    UpSever(u_int16_t port = defport)
        : _inet_addr(port),
          _isrunning(false),
          _sockfd(defsockfd)
    {
    }

    void SeverInit()
    {
        // 创建套接字
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "sock :" << strerror(SOCKET_ERR);
            Die(SOCKET_ERR);
        }

        LOG(LogLevel::INFO) << "sock sucess.";

        // 接入内核
        // struct sockaddr_in local;
        // // 清空
        // // bzero(&local, sizeof(local));
        // memset(&local, 0, sizeof(local));
        // 绑定
        // local.sin_family = AF_INET;
        // local.sin_port = htons(_port);
        // local.sin_addr.s_addr = INADDR_ANY;

        InetAddr inetlocal(_inet_addr);

        int n = ::bind(_sockfd, inetlocal.SockAddr(), inetlocal.SockLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind :" << strerror(BIND_ERR);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind sucess.";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char inbuffer[defsize];
            // 设定接受值
            struct sockaddr_in peer;
            socklen_t peer_len = sizeof(peer);

            int n = ::recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, Conv(&peer), &peer_len);
            if (n < 0)
            {
                LOG(LogLevel::FATAL) << "recvfrom fail";
                Die(RECV_ERR);
            }
            else
            {
                // 记录客户端信息
                // uint16_t cilent_port = ::ntohs(peer.sin_port);
                // std::string cilent_ip = ::inet_ntoa(peer.sin_addr);
                InetAddr sockpeer(peer);
                inbuffer[n] = 0;

                std::string cilentioform;
                cilentioform += sockpeer.Ip();
                cilentioform += ":";
                cilentioform += sockpeer.Port();
                cilentioform += " say # ";
                cilentioform += inbuffer;
                std::cout << cilentioform << std::endl;

                // 反馈
                ::sendto(_sockfd, cilentioform.c_str(), cilentioform.size(),
                         0, sockpeer.SockAddr(), sockpeer.SockLen());
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd; // 套接字文件描述符

    //u_int16_t _port;
   // std::string _ip;
    InetAddr _inet_addr;

    bool _isrunning; // 运行状态
};

#endif